define(['bootstrap','bootstrapTable','layer','bootstrapTableTreegrid','jqueryTreegrid'],function (bootstrap,bootstrapTable,layer,bootstrapTreegrid,jqueryTreegrid) {
    var parms={};
    return{
        init:function () {
            showData();
            /*添加角色*/
            $("#addRoles").click(function(){
                $("#rolesName").val("");
                $("#distribute").val("");
                openLayer("修改用户信息",$("#myRolesModal"))
            });
            /*授权*/
            $("#editRolePower").click(function(){
                var row = $('#bootstrapTable').bootstrapTable('getSelections');
                if (row.length == 1) {
                    layer.open({
                        type: 1,
                        title:'角色授权',
                        anim: 2,
                        closeBtn:1,
                        area:["60%","80%"],
                        content:$("#rolePower"),
                        cancel: function(index, layero){
                            $("#rolePowerTable").bootstrapTable('uncheckAll');
                            $("#rolePower").css({"display":"none"})
                        }
                    });

                    getTreeTable(row[0].id);
                    $("#rolePowerTable").bootstrapTable('uncheckAll');

                }else{
                    layer.msg("请选择要授权的角色！",{icon:1});
                }
            });
            /*关闭*/
            $(".btn_close").click(function(){
                $("#myRolesModal").css({"display":"none"})
                $("#rolePowerTable").bootstrapTable('uncheckAll');
                $("#rolePower").css({"display":"none"})
                layer.closeAll();
            });
            /*保存*/
            $("#btn_save").click(function(){
                $.ajax({
                    url:"/sysRoleController/add",
                    dataType:"json",
                    type:"post",
                    data:{
                        "roleName":$("#rolesName").val(),
                        "describes":$("#distribute").val(),
                    },
                    success:function(result){

                    }
                })
            });
            /*检索*/
            $("#search").click(function(){
                showData();
            });
            $("#sureRole").click(function(){
                var datas=[];
                var row=$("#rolePowerTable").bootstrapTable('getSelections');
                var pRow=$('#bootstrapTable').bootstrapTable('getSelections');
                if(row.length>0){
                    for(var i=0;i<row.length;i++){
                        datas.push(row[i].id);
                    };
                    $.ajax({
                        url:"/menuController/addUserPower",
                        traditional:true,
                        type:"post",
                        dataType:"json",
                        data:{rightIds:datas,rId:pRow[0].id},
                        success:function(result){
                            if(result.msg==="授权成功！"){
                                layer.msg("授权成功！",{icon:1});
                                setTimeout(function(){
                                    layer.closeAll();
                                },1000)
                            }else{
                                layer.msg("授权失败！",{icon:2});
                            }
                        }

                    })
                }else{
                    layer.msg("选择需要授权的菜单名称！",{icon:4});
                }

            })
        }
    };
    function openLayer(title,$dom){
        layer.open({
            type: 1,
            title:title,
            anim: 2,
            closeBtn:1,
            area:["60%","80%"],
            content:$dom,
            cancel: function(index, layero){
                $dom.css({"display":"none"})
            }
        });
    }
    function showData(){
        window.openEvent={
            'click #editor':function (e,value,row,index) {
                openLayer("修改用户信息",$("#myRolesModal"))
                $("#rolesName").val(row.actual_ip);
                $("#distribute").val(row.content);
            },
            'click #delete':function (e,value,row,index) {
                layer.confirm('您确定要删除此角色？', {title:'删除角色信息',icon: 2,
                    btn: ['确定','取消'] //按钮
                }, function(){
                    $.ajax({
                        url:"/sysRoleController/delById",
                        dataType:"json",
                        type:"post",
                        data:{
                            "id":row.id
                        },
                        success:function(result){
                            if(result.code==10001){
                                layer.msg("删除成功！",{icon:1});
                                layer.closeAll();
                                $('#bootstrapTree').bootstrapTable("refresh");
                            }else{
                                layer.msg("删除失败！",{icon:2});
                            }
                        }
                    })
                    layer.close();
                });
            }
        }
        $('#bootstrapTable').bootstrapTable({
            url: "/sysRoleController/pageSelect", // 获取表格数据的url
            method:'post',
            singleSelect:true,
            cache: false,       // 设置为 false 禁用 AJAX 数据缓存， 默认为true
            striped: true,      //表格显示条纹，默认为false
            pagination: true,   // 在表格底部显示分页组件，默认false
            pageList: [20,50,100], // 设置页面可以显示的数据条数
            pageSize: 20,       // 页面数据条数
            pageNumber: 1,      // 首页页码
            contentType:'application/x-www-form-urlencoded',
            sidePagination: 'server', // 设置为服务器端分页，必要
            queryParamsType : "",
            sortClass:'actual_ip',
            queryParams:function(params){
                return tem={
                    rows:params.pageSize,
                    page:params.pageNumber,
                    roleName:$("#setRole").val()
                }
            },
            idField: "actual_ip",  //标识哪个字段为id主键
            clickToSelect:false,
            columns: [
                {
                    title: '序号',
                    align: 'center',
                    formatter:showNumber,
                    width:'1%'
                } ,
                {
                    field: 'ck',
                    checkbox: true,
                    width:'1%'
                },
                {
                    field: 'roleName',
                    title: '角色名称',
                    align: 'center',
                    valign: 'middle',
                    width:'25%'

                }, {
                    field: 'describes',
                    title: '角色描述',
                    align: 'center',
                    valign: 'middle',
                    width:'20%'
                }, {
                    field: 'createUser',
                    title: "创建人",
                    align: 'center',
                    valign: 'middle',
                    width:'15%'
                },{
                    field:'createTime',
                    title:'创建时间',
                    align:'center',
                    valign:'middle',
                    width:'20%'
                }, {
                    field:'operator',
                    title: "操作",
                    align: 'center',
                    valign: 'middle',
                    events:openEvent,
                    formatter: function(value, row, index){
                        return ['<button class="btn btn-xs btn-info btn-operator-gew" id="editor"><i class="fa fa-edit"></i></button>','<button class="btn btn-xs btn-danger" id="delete"><i class="fa fa-trash-o"></i></button>'].join("");
                    }
                }
            ],
            onLoadSuccess: function(data){  //加载成功时执行

            },
            onLoadError: function(){  //加载失败时执行
            }
        });
    };
    //授权菜单
    function getTreeTable(id){
        var dataAll=[];
        $.ajax({
            url:'menuController/queryAllSysMenus',
            dataType:"json",
            data:{"id":id},
            success:function(result){
                for(var i=0,data=result;i<data.length;i++){
                    dataAll.push({id:data[i].id,name:data[i].text,pid:0,checked:data[i].checked});
                    if(data[i].children.length>0){
                        (function(i){
                            for(var j=0,_data=data[i].children;j<_data.length;j++){
                                dataAll.push({id:_data[j].id,name:_data[j].text,pid:data[i].id,checked:_data[j].checked})
                            }
                        })(i)
                    }
                };
                treeTable(dataAll,id)
            }
        })
    }

         /*授权树形表格*/
      function treeTable(_data,ids){
            var $table=$("#rolePowerTable");
          $table.bootstrapTable({
               data:_data,
               idField: 'id',
               treeCollapseAll: false,
               clickToSelect:true,
               columns: [
                   {
                       field: 'check',
                       checkbox: true,
                       formatter: function (value, row, index) {
                           if (row.check == true) {
                               //设置选中
                               return {  checked: true };
                           }
                       }
                   },
                   {
                        field: 'name',
                        title: '菜单名称'
                   }
               ],
               treeShowField: 'name',
               parentIdField: 'pid',
               onResetView: function(data) {
                   $table.treegrid({
                       initialState: 'expanded',// 所有节点都展开
                       treeColumn: 1,
                       expanderExpandedClass: 'fa fa-chevron-circle-down',
                       expanderCollapsedClass: 'fa fa-chevron-circle-right',
                       onChange: function() {
                           $table.bootstrapTable('resetWidth');
                       }
                   });

               }
           });
           for(var i=0;i<_data.length;i++){
               if(_data[i].checked===true){
                   $table.bootstrapTable('check',i);
               }
           }


      };
    function showNumber(value, row, index){
        var options = $('#bootstrapTable').bootstrapTable('getOptions');
        return options.pageSize*(options.pageNumber-1)+index + 1;
    }



})